package org.amf.gui;

import java.applet.AppletContext;
import java.awt.Cursor;
import java.net.URL;
import javax.swing.JLabel;
import org.amf.channel.ChannelInizializator;
import org.amf.helper.NicInspector;
import org.amf.helper.OsInspector;
import org.amf.message.RequestManager;

/**
 * La classe LoginJPanel e' la GUI applicativa
 *
 * @author Federico Casani
 */
public class LoginJPanel extends javax.swing.JPanel {

    private URL codeBase;
    private AppletContext appletContext;

    /** Creates new form LoginJPanel */
    public LoginJPanel(URL codeBase, AppletContext appletContext) {

        initComponents();

        // codeBase
        this.codeBase = codeBase;

        // appletContext
        this.appletContext = appletContext;

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        usernameTextField = new javax.swing.JTextField();
        usernameLabel = new javax.swing.JLabel();
        passwordLabel = new javax.swing.JLabel();
        statusLabel = new javax.swing.JLabel();
        passwordPasswordField = new javax.swing.JPasswordField();
        loginLabel = new javax.swing.JLabel();

        setBackground(new java.awt.Color(254, 254, 254));
        setName(""); // NOI18N
        setPreferredSize(new java.awt.Dimension(650, 250));

        usernameTextField.setName("username"); // NOI18N
        usernameTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                usernameTextFieldActionPerformed(evt);
            }
        });
        usernameTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                usernameTextFieldKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                usernameTextFieldKeyTyped(evt);
            }
        });

        usernameLabel.setText("Username");

        passwordLabel.setText("Password");

        statusLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        statusLabel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

        passwordPasswordField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                passwordPasswordFieldActionPerformed(evt);
            }
        });
        passwordPasswordField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                passwordPasswordFieldKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                passwordPasswordFieldKeyTyped(evt);
            }
        });

        loginLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        loginLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/amf/gui/entra_azzurro.gif"))); // NOI18N
        loginLabel.setAlignmentY(0.0F);
        loginLabel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        loginLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                loginLabelMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                loginLabelMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                loginLabelMouseExited(evt);
            }
        });
        loginLabel.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                loginLabelKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(statusLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 628, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(usernameLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(usernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(38, 38, 38)
                        .addComponent(passwordLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(passwordPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(loginLabel)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(66, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(usernameLabel)
                            .addComponent(usernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(passwordLabel)
                            .addComponent(passwordPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(52, 52, 52))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(loginLabel)
                        .addGap(54, 54, 54)))
                .addComponent(statusLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(49, 49, 49))
        );

        usernameLabel.getAccessibleContext().setAccessibleName("");
        passwordLabel.getAccessibleContext().setAccessibleName("");
    }// </editor-fold>//GEN-END:initComponents

    private void usernameTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_usernameTextFieldActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_usernameTextFieldActionPerformed

    private void passwordPasswordFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_passwordPasswordFieldActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_passwordPasswordFieldActionPerformed

    private void usernameTextFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_usernameTextFieldKeyTyped
        //

        this.statusLabel.setText("");

        //
    }//GEN-LAST:event_usernameTextFieldKeyTyped

    private void passwordPasswordFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_passwordPasswordFieldKeyTyped
        //

        this.statusLabel.setText("");

        //
    }//GEN-LAST:event_passwordPasswordFieldKeyTyped

    private void usernameTextFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_usernameTextFieldKeyReleased
        //

        int key = evt.getKeyCode();
        if (key == evt.VK_ENTER) {
            this.statusLabel.setText("");
            this.doLogin();
        } else {
            this.statusLabel.setText("");
        }

        //
    }//GEN-LAST:event_usernameTextFieldKeyReleased

    private void passwordPasswordFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_passwordPasswordFieldKeyReleased
        //

        int key = evt.getKeyCode();
        if (key == evt.VK_ENTER) {
            this.statusLabel.setText("");
            this.doLogin();
        } else {
            this.statusLabel.setText("");
        }

        //
    }//GEN-LAST:event_passwordPasswordFieldKeyReleased

    private void loginLabelMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_loginLabelMouseExited
        //

        this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));

        //
    }//GEN-LAST:event_loginLabelMouseExited

    private void loginLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_loginLabelMouseEntered
        //

        this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        //
    }//GEN-LAST:event_loginLabelMouseEntered

    private void loginLabelKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_loginLabelKeyReleased
        //

        int key = evt.getKeyCode();
        if (key == evt.VK_ENTER) {
            this.statusLabel.setText("");
            this.doLogin();
        } else {
            this.statusLabel.setText("");
        }

        //
    }//GEN-LAST:event_loginLabelKeyReleased

    private void loginLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_loginLabelMouseClicked
        //

        this.doLogin();

        //
    }//GEN-LAST:event_loginLabelMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel loginLabel;
    private javax.swing.JLabel passwordLabel;
    private javax.swing.JPasswordField passwordPasswordField;
    private javax.swing.JLabel statusLabel;
    private javax.swing.JLabel usernameLabel;
    private javax.swing.JTextField usernameTextField;
    // End of variables declaration//GEN-END:variables

    private void doLogin() {


        try {

            // reset
            this.statusLabel.setText("");

            // controllo dati inseriti
            if (this.usernameTextField.getText().trim().length() == 0 || new String(this.passwordPasswordField.getPassword()).trim().length() == 0) {

                this.statusLabel.setText("Inserire dati corretti");

            } else {

                /*
                 * OS inspection
                 */
                OsInspector osInspector = new OsInspector();
                
                /*
                 * NIC inspection
                 */
                NicInspector nicInspector = new NicInspector();

                /*
                 * MESSAGE gestito dal Channel
                 */
                RequestManager requestManager = new RequestManager(this, nicInspector, osInspector);

                /*
                 * HTTP/HTTPS POST
                 */
                ChannelInizializator channelInizializator = new ChannelInizializator(this.getCodeBase(), requestManager.getMessage());
                // TODO aggiungere Exception "protocollo non supportato"
                switch (channelInizializator.getStatusResponse()) {

                    case ChannelInizializator.HTTP_SC_OK:

                        this.getStatusLabel().setText("Autenticazione eseguita correttamente");

                        try {
                            this.getAppletContext().showDocument(new URL(channelInizializator.getUrlFORWARD()), "_self");
                        } catch (Exception e) {
                            this.getStatusLabel().setText("Autenticazione fallita: applet error");
                        }
                        break;

                    case 0:
                        this.getStatusLabel().setText("Autenticazione fallita");
                        break;

                    default:
                        
                        this.getStatusLabel().setText("Autenticazione fallita:  error " + channelInizializator.getStatusResponse());
                }
            }



        } catch (Exception e) {
            
            this.statusLabel.setText("Autenticazione fallita");
        }


    }

    public URL getCodeBase() {
        return codeBase;
    }

    public void setCodeBase(URL codeBase) {
        this.codeBase = codeBase;
    }

    public void setStatusLabel(JLabel statusLabel) {
        this.statusLabel = statusLabel;
    }

    public JLabel getStatusLabel() {
        return statusLabel;
    }
    
    public AppletContext getAppletContext() {
        return appletContext;
    }

    public void setAppletContext(AppletContext appletContext) {
        this.appletContext = appletContext;
    }

    public String getUsernameTextFieldText() {
        return this.usernameTextField.getText();
    }

    public String getPasswordPasswordFieldText() {
        if (this.passwordPasswordField.getPassword()!= null) return new String(this.passwordPasswordField.getPassword());
        else return "";
    }


    
}
